package com.bankcomm.luafuction;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaState;

import android.app.Activity;

import com.bankcomm.common.ConfigManager;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.offstore.OffStoreDB;
import com.rytong.tools.offstore.OffStoreDownload;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

public class LuaFile {
    public LuaFile() {
        try {
            Component.LUASTATE.pushObjectValue(this);
            Component.LUASTATE.setGlobal("luafile");
            final String luahead = "file = {}; ";
            final String luafc1 = "function file:write(name,data) luafile:write(name,data); end;";
            final String luafc2 = "function file:read(name,type) local a1 = luafile:read(name,type); return a1; end;";
            final String luafc3 = "function file:remove(name) luafile:remove(name); end;";
            final String luafc4 = "function file:isExist(name) local a1 = luafile:isExist(name); return a1; end";
            Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
            Component.LUASTATE.LdoString(luahead.concat(luafc1).concat(luafc2).concat(luafc3).concat(luafc4));
        } catch (LuaException e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    /**
     * write接口写的文件，必要保存到单独的路径下。与离线资源，插件资源的路径分开.
     * 
     * 即：OffStoreDownload.WRITEROOT
     * */
    public void write(Object name, Object data) {
        String fileName = null;
        if (name instanceof String)
            fileName = (String) name;
        try {
            byte[] bytes = null;
            String root = OffStoreDownload.WRITEROOT;
            Utils.saveFile(root, bytes);
            if (data instanceof String) {
                bytes = ((String) data).getBytes();
            } else {
                bytes = (byte[]) data;
            }
            Utils.saveFile(root.concat(fileName), bytes);
        } catch(Exception e){
            Utils.printException(e);
        }
    }
    
    /**
     * 插件资源 > 离线下载资源 > file：write写出的资源 > 安装包资源
     * */
    public boolean isExist(Object name) {
    	String fileName = "";
        if (null == name)
            return false;
        else
            fileName = name.toString();

        byte[] buffer = null;
        buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.PLUGROOT).concat(fileName));
        if (null == buffer)
            buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.OFFLINEROOT).concat(fileName));
        if(null == buffer){
        	File tempFile = new File(fileName);
        	String filePath = "";
        	if (Utils.getMIMEType(tempFile).equalsIgnoreCase("image")) {
        		filePath = "images/";
        	} else if(Utils.getMIMEType(tempFile).equalsIgnoreCase("audio")){
        		filePath = "audios/";
        	} else if(Utils.getMIMEType(tempFile).equalsIgnoreCase("video")){
        		filePath = "videos/";
        	}
        	String content = Utils.getStringFormAsset(ConfigManager.currentView_, filePath + fileName);
        	if(!content.equals("")){
        		buffer = content.getBytes();
        	}
        }
        if (null == buffer) {
            buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.WRITEROOT).concat(fileName));
        }
        if (null == buffer)
            return false;
        else
            return true;
    }

    /**
     * 优先级顺序为：插件资源 > 离线下载资源 > file：write写出的资源 > 安装包资源
     * */
    public Object read(Object name, Object type) {
    	if(name == null)
    		return null;
        String fileName = null;
        String fileType = null;
        FileInputStream fis = null;
        byte[] buffer = null;
        String s = null;
        if (name instanceof String)
            fileName = (String) name;
        if (type instanceof String)
            fileType = (String) type;
        try {
        	String fPath = OffStoreDB.readOffline(OffStoreDB.OFFLINEDB, fileName);
        	if(null == fPath){
        		fPath = OffStoreDB.readOffline(OffStoreDB.PLUGDB, fileName);
        	}
            buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.PLUGROOT).concat(fPath));
            if (null == buffer)
                buffer = Utils
                        .readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.OFFLINEROOT).concat(fPath));
            if (null == buffer) {
                buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.WRITEROOT).concat(fPath));
            }
            if(null == buffer){
            	File tempFile = new File(fileName);
            	String filePath = "";
            	if (Utils.getMIMEType(tempFile).equalsIgnoreCase("image")) {
            		filePath = "images/";
            	} else if(Utils.getMIMEType(tempFile).equalsIgnoreCase("audio")){
            		filePath = "audios/";
            	} else if(Utils.getMIMEType(tempFile).equalsIgnoreCase("video")){
            		filePath = "videos/";
            	}
            	String content = Utils.getStringFormAsset(ConfigManager.currentView_, filePath + fileName);
            	if(!content.equals("")){
            		buffer = content.getBytes();
            	}
            }
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                    fis = null;
                } catch (IOException e) {
                    Utils.printException(e);
                }
            }
        }
        if (null == buffer)
            return null;
        if (fileType != null && fileType.equals("text")) {
            try {
                s = new String(buffer, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                Utils.printException(e);
            }
            return s;
        } else if (fileType != null && fileType.equals("image")) {
            return buffer;
        } else { // 其他类型，也返回二进制数据
            return buffer;
        }

    }

    /**
     * 只能删除file:write写进去的文件
     * */
    public void remove(Object name) {
        String fileName = "";
        if (null == name || name.equals(""))
            return;
        else
            fileName = name.toString();

        File file = new File(OffStoreDownload.FILEROOT.concat(OffStoreDownload.WRITEROOT).concat(fileName));
        if (file.exists()) {
            file.delete();
        }

    }
}
